<template>
  <div id="TenantManagement">
    <el-card
      shadow="always"
      :v-loading="loading"
      :body-style="{ padding: '20px', height: '100%' }"
    >
      <!-- card body -->
      <el-row type="flex" justify="space-around" style="height: 40px">
        <el-col :span="1" :offset="0"></el-col>
        <el-col :span="22" :offset="0" style="text-align: left">
          <el-button-group style="width: 680px">
            <el-button
              type="success"
              size="default"
              @click="addTenant"
              icon="el-icon-plus"
              >新增</el-button
            >
            <el-button
              type="success"
              size="default"
              @click="bulk_import.dialog_status=true"
              icon="el-icon-plus"
              >批量新增</el-button
            >
            <el-button
              type="danger"
              size="default"
              icon="el-icon-delete"
              @click="batchDeleteTenant"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="default"
              icon="el-icon-refresh"
              @click="resetList"
              >重置</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-search"
              size="default"
              @click="getSearchList"
              >搜索</el-button
            >
            <el-input
              v-model="search"
              placeholder="请输入名称"
              size="normal"
              @change="getSearchList"
              clearable
              style="width: 200px"
            ></el-input>
          </el-button-group>
        </el-col>
        <el-col :span="1" :offset="0"></el-col>
      </el-row>

      <el-row type="flex" justify="space-around" style="margin-top: 5px">
        <el-col :span="1" :offset="0"></el-col>
        <el-col :span="22" :offset="0">
          <el-table
            :data="tenant_list"
            height="700"
            style="font-size: 0.9rem; text-align: center; width: 100%"
            @selection-change="setDelList"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
              type="expand"
              v-if="mode == 0 ? true : false"
              width="55"
            >
              <template slot-scope="scope">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="应收房租：">
                    <el-row :gutter="0" style="width: 300px">
                      <el-col :span="8" :offset="0"
                        ><span>{{ scope.row.guest_price + "元" }}</span></el-col
                      >
                      <el-col :span="16" :offset="0">
                        <el-tag
                          :type="
                            scope.row.guest_price_type ? 'success' : 'danger'
                          "
                          effect="dark"
                          >{{
                            scope.row.guest_price_type ? "已收" : "未收"
                          }}</el-tag
                        >
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item label="应收电费：">
                    <el-row :gutter="0" style="width: 300px">
                      <el-col :span="8" :offset="0"
                        ><span>
                          {{ scope.row.guest_electric_price + "元" }}</span
                        ></el-col
                      >
                      <el-col :span="16" :offset="0"
                        ><el-tag
                          :type="
                            scope.row.guest_electric_price_type
                              ? 'success'
                              : 'danger'
                          "
                          effect="dark"
                          >{{
                            scope.row.guest_electric_price_type
                              ? "已收"
                              : "未收"
                          }}</el-tag
                        >
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item label="应收水费：">
                    <el-row :gutter="0" style="width: 300px">
                      <el-col :span="8" :offset="0"
                        ><span>{{
                          scope.row.guest_water_price + "元"
                        }}</span></el-col
                      >
                      <el-col :span="16" :offset="0"
                        ><el-tag
                          :type="
                            scope.row.guest_water_price_type
                              ? 'success'
                              : 'danger'
                          "
                          effect="dark"
                          >{{
                            scope.row.guest_water_price_type ? "已收" : "未收"
                          }}</el-tag
                        >
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column prop="guest_name" label="住户姓名">
            </el-table-column>
            <el-table-column prop="guest_phone" label="手机号码">
            </el-table-column>
            <el-table-column prop="guest_nbr" label="身份证"> </el-table-column>
            <el-table-column label="合同期限">
              <template slot-scope="scope">
                {{ scope.row.guest_date1 }}<br />{{ scope.row.guest_date2 }}
              </template>
            </el-table-column>
            <el-table-column
              prop="guest_start_date"
              v-if="mode == 0 ? true : false"
              label="下次计费时间"
            >
            </el-table-column>
            <el-table-column label="距合同到期（天）">
              <template slot-scope="scope">
                {{ getDeadLine(scope.row.guest_date2) }}
              </template>
            </el-table-column>
            <el-table-column prop="guest_network_name" label="绑定的网络账号">
            </el-table-column>
            <el-table-column
              align="right"
              fixed="right"
              :width="showChargeDetail==true ? 240 : 440"
            >
              <template slot="header" slot-scope="scope"> 操作</template>
              <template slot-scope="scope">
                <el-button
                  type="warning"
                  size="medium"
                  icon="el-icon-coin"
                  v-show="$store.state.mode == 0"
                  @click="
                    setRentData(
                      scope.row.guest_id,
                      scope.row.guest_price_type,
                      scope.row.guest_electric_price_type,
                      scope.row.guest_water_price_type,
                      scope.row.guest_network_price_type
                    )
                  "
                  >记账</el-button
                >

                <el-button
                  v-show="showChargeDetail()"
                  type="primary"
                  size="medium"
                  icon="el-icon-setting"
                  @click="
                    setTenantStartDate(
                      scope.row.guest_start_date,
                      scope.row.guest_id,
                      scope.row.guest_about_house_id
                    )
                  "
                  >开始计费时间</el-button
                >

                <el-button
                  type="primary"
                  size="medium"
                  icon="el-icon-edit-outline"
                  @click="modifyTenant(scope.row)"
                ></el-button>
                <el-button
                  type="danger"
                  size="medium"
                  icon="el-icon-delete"
                  @click="
                    deleteTenant(
                      scope.row.guest_id,
                      scope.row.guest_network_name
                    )
                  "
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="1" :offset="0"></el-col>
      </el-row>
      <el-row
        :gutter="0"
        type="flex"
        justify="space-between"
        style="margin-top: 5px"
      >
        <!-- 分页插件 -->
        <el-col :span="1" :offset="0"></el-col>
        <el-col :span="22" :offset="0">
          <el-pagination
            background
            layout="total,prev, pager, next,jumper"
            :page-size="20"
            :total="tenant_total"
            @current-change="getTenantList"
            :current-page.sync="page_num"
          >
          </el-pagination>
        </el-col>
        <el-col :span="1" :offset="0"></el-col>
      </el-row>
    </el-card>
    <!-- 新增/修改的抽屉 -->
    <el-drawer
      :visible.sync="tenant_drawer_status"
      direction="rtl"
      size="auto"
      :destroy-on-close="true"
      :show-close="true"
      :wrapperClosable="false"
    >
      <h1>住户数据</h1>
      <el-divider direction="horizontal"></el-divider>
      <tenant-information
        :type="tenant_drawer_type"
        :information="modify_tenant_information"
        @getList="getTenantList"
        @closeDrawer="closeTenantDrawer"
        style="margin-right: 20px"
      ></tenant-information>
    </el-drawer>
    <!-- 设定住户开始计费时间 -->
    <el-dialog
      title="设定住户开始计费时间"
      :visible.sync="tenant_start_date_dialog_status"
      width="300px"
    >
      <el-date-picker
        v-model="tenant_start_date"
        type="date"
        size="normal"
        format="yyyy-MM-dd"
        style="width: 100%"
        value-format="yyyy-MM-dd"
        placeholder="选择日期"
      >
      </el-date-picker>
      <span slot="footer">
        <el-button @click="tenant_start_date_dialog_status = false"
          >关闭</el-button
        >
        <el-button type="primary" @click="modifyTenantStartDate"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <!-- 记账 -->
    <el-dialog
      title="记账"
      :visible.sync="rent.dialog_status"
      width="400px"
      style="text-align: center"
      @open="rent.active_list = []"
    >
      <el-checkbox-group v-model="rent.active_list">
        <el-checkbox-button
          v-for="item in rent.list"
          :label="item.key"
          :key="item.key"
          >{{ item.name }}</el-checkbox-button
        >
      </el-checkbox-group>
      <span slot="footer">
        <el-button @click="rent.dialog_status = false">关闭</el-button>
        <el-button type="primary" @click="rentSubmit">确定</el-button>
      </span>
    </el-dialog>
    <!-- 批量导入 -->
    <el-dialog
      title="批量新增"
      :visible.sync="bulk_import.dialog_status"
      width="366px"
      @close="bulk_import.percentage=0"
    >
      <el-button type="primary" size="default" icon="el-icon-download" @click="downloadFile">导入模板下载</el-button>
      <el-divider direction="vertical"></el-divider>
      <el-upload
          style="display:inline-block"
          action=""
          :show-file-list="false"
          :on-preview="uploadFile"
          :auto-upload="false"
          accept=".xls"
          :limit="1"
          :on-change="uploadFile"
          :file-list="bulk_import.file_list"
        >
        <el-button type="success" size="default" icon="el-icon-upload2">上传文件导入</el-button>
        </el-upload>
        <span slot="footer">
          <span style="float: left;margin-bottom:10px">上传进度</span>
        <el-progress :text-inside="true" :stroke-width="26" :percentage="bulk_import.percentage"></el-progress>
      </span>
    </el-dialog>
    
    
  </div>
</template>

<script>
import TenantInformation from "./TenantInformation.vue";
import utils from "@/store/timeTotimestr.js";

export default {
  name: "TenantManagement",
  data() {
    return {
      tenant_list: [], //渲染列表
      tenant_total: 0, // 总数据量
      search: "", // 搜索框内容
      search_status: false, // 搜索状态控制
      search_data: [], // 搜索结果数据
      page_num: 1, // 控制页码
      tenant_drawer_status: false, // 控制抽屉的开关
      tenant_drawer_type: "add", // 控制抽屉类型
      modify_tenant_information: {}, // 类型为修改时给到相关信息
      del_list: [], // 删除列表
      tenant_start_date_dialog_status: false, // 设定住户开始计费时间的对话框状态
      tenant_start_date: "", // 要设定的开始时间
      tenant_id: "", // 住户id
      house_id: "", // 住户所在房间的id
      rent: {
        dialog_status: false,
        list: [],
        active_list: [],
      },
      loading: false,
      mode: this.$store.state.mode,
      bulk_import:{
        dialog_status:false,
        file_path:"../../../static/data.xls",
        file_list:[],
        percentage:0
      }
    };
  },
  methods: {
    getTenantList() {
      if (!this.search_status) {
        this.$axios({
          method: "post",
          url: "/api/guestapi/dispatcher",
          data: {
            action: "list",
            page_max: "20",
            page: this.page_num,
            openid: localStorage.getItem("unionid"),
          },
        }).then((res) => {
          this.tenant_total = res.data.count;
          this.tenant_list = res.data.data;
        });
      } else {
        this.tenant_list = [];
        let start_data_num = (this.page_num - 1) * 20; // 20条数据为一页，记录到开始数据序号
        let paging = 0;
        for (let i = start_data_num; i < this.tenant_total; i++) {
          if (paging > 19) {
            return;
          } else {
            this.tenant_list[i] = this.search_data[i]; // 重新赋值
          }
          paging++;
        }
      }
    },
    addTenant() {
      this.tenant_drawer_status = true;
      this.tenant_drawer_type = "add";
    },
    modifyTenant(information) {
      this.tenant_drawer_status = true;
      this.tenant_drawer_type = "modify";
      this.modify_tenant_information = information;
    },
    batchDeleteTenant() {
      this.$confirm(
        "确认是否删除这些住户，注意：若住户有入住房间，则会自动退租他所在的房间",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let _list = [];
          for (let item of this.del_list) {
            if(item.guest_network_name==null){
              _list.push(item.guest_id);
            }
          }
          if (_list.length == 0) {
            this.$message.error("请先选中任意住户再进行操作或住户中存在有已经绑定了网络账号的，请删除对应的网络账号后继续");
          } else {
            this.$axios({
              method: "post",
              url: "/api/guestapi/dispatcher",
              data: {
                action: "del",
                guest_id: _list,
              },
            }).then((res) => {
              if (res.data.ret == 0) {
                this.$message.success("删除住户成功");
                this.page_num = 1;
                this.getTenantList();
              } else {
                this.$message.error("删除住户失败");
              }
            });
          }
        })
        .catch(() => {});
    },
    deleteTenant(val, network_name) {
      this.$confirm(
        "确认是否删除该住户，注意：若住户有入住房间，则会自动退租他所在的房间",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          if (network_name == null) {
            this.$axios({
              method: "post",
              url: "/api/guestapi/dispatcher",
              data: {
                action: "del",
                guest_id: [val],
              },
            }).then((res) => {
              if (res.data.ret == 0) {
                this.$message.success("删除住户成功");
                this.page_num = 1;
                this.getTenantList();
              } else {
                this.$message.error("删除住户失败");
              }
            });
          } else {
            this.$alert(
              `删除失败，该住户存在网络账号${network_name},请先删除相应的账号后再继续`,
              "提示",
              {
                type: "error",
              }
            );
          }
        })
        .catch(() => {});
    },
    getSearchList() {
      this.search_status = true;
      this.$axios({
        method: "POST",
        url: "/api/guestapi/dispatcher",
        data: {
          action: "like",
          guest_name: this.search,
          openid: localStorage.getItem("unionid"),
        },
      }).then((res) => {
        this.search_data = res.data.data;
        this.page_num = 1;
        this.tenant_total = res.data.data.length;
        this.getTenantList();
      });
    },
    setDelList(val) {
      this.del_list = val;
    },
    resetList() {
      this.search_status = false;
      this.page_num = 1;
      this.getTenantList();
    },
    getDeadLine(end_date) {
      let now = new Date();
      let _date = utils.getNowTime(now).now_date;
      let _start_date = new Date(_date);
      let _end_date = new Date(end_date);
      return (_end_date - _start_date) / 86400000;
    },
    setTenantStartDate(start_date, id, house_id) {
      this.tenant_start_date_dialog_status = true;
      this.tenant_start_date = start_date;
      this.tenant_id = id;
      this.house_id = house_id;
    },
    modifyTenantStartDate() {
      let action = "set";
      let set_type = "guest";
      let guest_id = this.tenant_id;
      let guest_start_date = this.tenant_start_date;
      const tenant_data = { action, set_type, guest_id, guest_start_date };
      this.$axios({
        method: "post",
        url: "/api/guestapi/dispatcher",
        data: tenant_data,
      }).then((res) => {
        if (res.data.ret == 0) {
          this.$message.success("设定开始计费时间成功");
          this.getTenantList();
          this.tenant_start_date_dialog_status = false;
        } else {
          this.$message.error("设定开始计费时间失败");
        }
      });
    },
    setRentData(id, price_type, electric_type, water_type) {
      this.rent.dialog_status = true;
      this.tenant_id = id;
      this.rent.list = [];
      price_type == 0
        ? this.rent.list.push({ name: "房租", key: "house" })
        : false;
      electric_type == 0
        ? this.rent.list.push({ name: "电", key: "electric" })
        : false;
      water_type == 0
        ? this.rent.list.push({ name: "水", key: "water" })
        : false;
      if (this.rent.list.length == 0) {
        this.rent.dialog_status = false;
        this.$message.success("该住户已收齐相关费用");
      }
    },
    rentSubmit() {
      this.loading = true;
      this.$confirm("确认是否收租,注意：此操作不可逆", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "post",
            url: "/api/guestapi/dispatcher",
            data: {
              action: "price", //控制参数
              price_type: this.rent.active_list, //house= 房租  electric= 电费  water= 水费  all=全部已收
              guest_id: this.tenant_id,
            },
          })
            .then((res) => {
              if (res.data.ret == 0) {
                this.$message.success("记账成功");
                this.rent.dialog_status = false;
                this.getTenantList();
              } else {
                this.$message.error(`记账失败,${res.data.msg}`);
              }
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    closeTenantDrawer() {
      this.tenant_drawer_status = false;
    },
    showChargeDetail() {
      console.log(this.$store.state.mode);
      if (this.$store.state.mode == "0") {
        return true;
      } else {
        return false;
      }
    },
    downloadFile(){
      window.open(this.bulk_import.file_path,"_blank");
    },
    uploadFile(e){
      if(e.raw.type!="application/vnd.ms-excel"){
        this.$message.error("请上传.xls格式的文件");
        this.bulk_import.file_list=[];
      }else{
        let form_data=new FormData();
        form_data.append('file',e.raw);
        form_data.append('guest_openid',this.$store.state.unionid);
        this.$axios({
          method:'post',
          url: "/api/toolapi/excel",
          data:form_data,
          onUploadProgress: progressEvent=>{
            const complete = parseInt((progressEvent.loaded / progressEvent.total * 100 | 0));
            this.bulk_import.percentage=complete;
          }
        }).then(res=>{
          if(res.data.ret==0){
            this.$message.success("导入文件成功");
            this.bulk_import.file_list=[];
            this.bulk_import.percentage=0;
            this.bulk_import.dialog_status=false;
            this.getTenantList();
          }else{
            this.$message.error(`导入文件失败,失败原因:${res.data.msg}`);
            this.bulk_import.file_list=[];
            this.bulk_import.percentage=0;
            this.bulk_import.dialog_status=false;
            this.getTenantList();
          }
        })
      }
    }
  },
  mounted() {
    this.getTenantList();
  },
  components: {
    TenantInformation,
  },
};
</script>

<style scoped>
#TenantManagement,
.el-card {
  height: 100%;
  overflow: hidden;
  overflow-x: auto;
}

.el-table {
  width: 100%;
}
</style>

<style>
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: rgb(200, 200, 200);
}

#TenantManagement .el-table td,
#TenantManagement .el-table th {
  text-align: center;
  font-size: 15px;
}

#TenantManagement .el-table th {
  background-color: #ecf5ff;
}

h1 {
  margin: 10px auto;
  text-align: center;
  font-size: 1.6rem;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
  text-align: left;
}
.demo-table-expand .el-form-item span {
  margin-right: 10px;
}
</style>
